<?php

namespace Admin\Controller;

class UserController extends ComController
{
    public function index()
    {

        $p         = I('get.p',1, 'intval');
        // $field     = isset($_GET['field']) ? $_GET['field'] : '';
        $field    = I('get.field','');
        $keyword   = trim(I('get.keyword','','htmlspecialchars'));
        $starttime = I('get.starttime','');
        $endtime   = I('get.endtime','');

        $order    = I('get.order','DESC');
        $where = array();

        if ($order == 'asc') {
            $order = "createtime asc";
        } elseif (($order == 'desc')) {
            $order = "createtime desc";
        } else {
            $order = "createtime asc";
        }

        if (!empty($keyword)) {
            switch($field){
                case 'user':
                $map['user_name'] =  array('like',"%$keyword%");
                break;

                case 'phone':
                $map['mobile_phone'] =  array('like',"%$keyword%");
                break;
                // case 'user':
                // $map['user_name'] =  array('like'=>'%$keyword%');
                // break;
            }
        }

        if (!empty($starttime)) {
            $map['createtime'][] = array('gt',$starttime);
        }

        if (!empty($endtime)) {
            $map['createtime'][] = array('lt',$endtime);
        }

        $user = M('users');
        $pagesize = 10;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量

        $count = $user->where($map)->count();

        $field = 'user_id id,user_name name,mobile_phone phone, user_points score,createtime, status';
        $list = $user->order($order)
        ->field($field)
        ->where($map)
        ->limit($offset . ',' . $pagesize)
        ->select();


        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->display();
    }

    public function del()
    {
        $uids = I('get.ids',false);

        if (is_array($uids)) {
            foreach ($uids as $k => $v) {
                if ($v == 1) {//uid为1的禁止删除
                    unset($uids[$k]);
                }
                $uids[$k] = intval($v);
            }

            if (!$uids) {
                $this->error('参数错误！');
                $uids = implode(',', $uids);
            }
        }

        $map['user_id'] = array('in', $uids);
        $res = M('users')->where($map)->save(array('status'=>0));

        if (false !== $res) {
            addlog('删除会员UID：' . $uids);
            return $this->success('恭喜，用户删除成功！');
        } else {
            return $this->error('参数错误！');
        }
    }

    public function edit()
    {
        $uid = I('get.id', false);

        if (!$uid) {
            return $this->error('参数错误！');
        }

        $field = 'user_id id, user_name name, mobile_phone phone,birthday,status,sex, car_no carno';

        $info = D('users')->getInfo($uid, $field);

        $this->assign('info', $info);
        return $this->display();
    }

    public function update()
    {
        $data = I('post.');

        if (!isset($data['uid']) || empty($data['uid'])) {
            $this->error('参数错误！');
        }


        $userInfo = array(
            'sex'          => intval($data['sex']),
            'birthday'     => trim($data['birthday']),
            'mobile_phone' => trim($data['phone']),
            'car_no'       => trim($data['carno']),
            // 'qq'        => trim($data['qq']),
            // 'email'        => intval($data['email']),
        );

        $res = D('users')->updInfo($data['uid'], $userInfo);

        if (!$res) {
            return $this->error('操作失败');
        }

        return $this->success('操作成功！','index');
    }

    //积分
    public function scoretran($id)
    {
        // $id = I('get.id', '');

        if (empty($id)) {
            $this->error('参数错误！');
        }

        $fields = 'user_id id, user_name name, user_points score';

        $info = D('users')->getInfo($id, $fields);

        if (empty($info)) {
            $this->error('获取用户信息失败');
        }

        $this->assign('info', $info);
        $this->display();
    }

    public function savescore()
    {
        if (!IS_POST) {
            $this->error('请求方式错误');
        }

        $data = I('post.');

        if (!isset($data['uid']) || empty($data['uid'])) {
            $this->error('参数错误！');
        }

        if (!isset($data['score']) || empty($data['score'])) {
            $this->error('参数错误！');
        }

        if (intval($data['score']) > 1) {
            $busid = '10103';
            $type = 1;
        }else{
            $busid = '10203';
            $type = -1;
        }

        $id         = intval($data['uid']);
        $scoreModel = D('ScoreTran');
        $score      = $data['score'] - 0;

        $res = $scoreModel->tran($busid, $id, $type, $score, '雇员后台操作修改积分。'.$data['memo'], session('uid'));

        // echo $scoreModel->getError();exit;

        if (!$res) {
            return $this->error('操作失败!');
        }

        addlog('修改用户的积分');

        return $this->success('操作成功!', 'index');
    }

    public function scorelog($id){
        if (empty($id)) {
            return $this->error('操作失败!');
        }

        $list = D('ScoreTran')->getLogByUid($id);

        $this->assign('list',$list);
        $this->display();
        // $this->ajaxReturn(array('asf'=>1));
    }

    //导出会员
    public function export(){
        $conditions = I('param.');
        $starttime  = I('param.starttime','');
        $endtime    = I('param.endtime','');

        ini_set('max_execution_time', '200');
        // set_time_limit(120);
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.IOFactory');
        $objPHPExcel = new \PHPExcel();

        $map = array();
        $m = M('users');

        if (!empty($starttime)) {
            $map['createtime'][] = array('gt',$starttime);
        }

        if (!empty($endtime)) {
            $map['createtime'][] = array('lt',$endtime);
        }

        $list = $m->where($map)->order('createtime desc')->select();

        // echo $m->getLastSql();exit;
        // print_r($list);exit;

        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', 'ID')
        ->setCellValue('B1', '用户名')
        ->setCellValue('C1', '性别')
        ->setCellValue('D1', '生日')
        ->setCellValue('E1', '车牌')
        ->setCellValue('F1', '注册时间');

         $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
         $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
         $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);

        $fileName = date('YmdHis').mt_rand(1000,9999);
        $fileName = iconv("utf-8", "gb2312", $fileName);

        if (!empty($list)) {
            foreach ($list as $k=>$v) {
                $newKey = $k+2;
                $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$newKey, $v['user_id'])
                ->setCellValue('B'.$newKey, $v['user_name'])
                ->setCellValue('C'.$newKey, $v['sex'])
                ->setCellValue('D'.$newKey, $v['birthday'])
                ->setCellValue('E'.$newKey, $v['car_no'])
                ->setCellValue('F'.$newKey, $v['createtime']);
            }
        }

        $title = '会员列表';
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($title);
        // print_r($objPHPExcel->getActiveSheet());exit;
        // $objPHPExcel->getActiveSheet(0)->setTitle($title);

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $title . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        ob_end_clean();
        $objWriter->save('php://output');
        exit;
    }
}
